# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import typing as t

from bs4 import BeautifulSoup

from ksai.document.context import DocumentSection
from ksai.document.extractor.extractor import AbstractDocumentExtractor, DocumentExtractorException
from ksai.persistence.storage.attachment import Attachment


class HtmlDocumentExtractor(AbstractDocumentExtractor):

    def __init__(self):
        super().__init__()

    def do_extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        try:
            soup = BeautifulSoup(attachment.content_string, "html.parser")
            text = soup.get_text()
            return [DocumentSection(
                text=text.strip() if text else "",
            )]
        except Exception as e:
            raise DocumentExtractorException(f"Extract HTML/XML file error: {e}") from e

    def extensions(self) -> t.List[str]:
        return ["html", "htm", 'xml']

    def mimes(self) -> t.List[str]:
        return ["text/html", "text/htm", "text/xml"]
